<?php
namespace app\index\controller;
use app\common\model\AdminUser;
use app\index\Controller;
use think\Db;
use think\Validate;
use Rbac;
use think\Config;
/**
 * @title 登录注册（模块01）
 * @description 接口说明
 * @groupremark 已使用错误码： 1010001 1010002 1010003 1010004 1010005 1010006 1010007 1010008 1010009 1010010 1010011 1010012 1010013 1010014 1010015 1010016
 * @group 用户
 * @header name:model_id   default:01 desc:模块id
// * @param name:token type:string   default:  other: desc: token
 */
class Login extends Controller
{
    /**
     * @var array 白名单方法，如果设置会覆盖黑名单方法，只允许白名单方法能正常访问
     */
    protected static $allowList = ['index','register','code','updatepwd','updatephone'];


    /**
     * @title 登录
     * @description 接口说明
     * @author 梁敏
     * @url /index/login/index
     * @method ~
     * @param name:account type:string require:1
     * @param name:password type:string require:1
     * @return token:token
     * @return data:用户信息@!
     * @data name:名称 user_id:用户id
     * @return error_id: 1010003 校验错误,1010004 校验错误
     */

    public function index()
    {

        //接口代码
        $data=$this->request->param();

        //校验错误
        $validate = new \app\common\validate\AdminUser();
        $v_re = $validate->scene('login')->check($data);
        if(!$v_re){
            $msg['error_id']='1010003';
            $msg['message']=$validate->getError();
            $msg['data']=$validate->getError();
            return $this->error($msg);
        }
        // 查找是否存在该账号
        $account = Db::name('admin_user')->where('account',$data['account'])->find();
        if (!$account){
            $msg['error_id']='1010004';
            $msg['message']='不存在该账号,请先注册!';
            $msg['data']=$data;
            return $this->error($msg);
        }
        $map['account']=$data['account'];
        $map['password']=password_hash_tp($data['password']);
        $auth_info=Db::name('admin_user')->where($map)->find();
        if($auth_info&&$auth_info['status']>0&&$auth_info['isdelete']==0){
            // 验证是否已经填写司导信息
            $driverFind = Db::name('driver')->where('user_id', $auth_info['id'])->find();
            if (!$driverFind){
                $msg['error_id']='1010004';
                $msg['message']='你还没有填写司导信息';
                $msg['is_write'] = 1; // 未填写返回1,已填写司机信息返回0
                return $this->error($msg);
            }
            $token=get_token();
            Db::name('admin_user')->where('id',$auth_info['id'])->update(array('token'=>$token));
            $msg['is_write'] = 0;
            $msg['message']="登录成功";
            $msg['token']=$token;
            unset($auth_info['password']);
            $msg['data']=$auth_info;

            // 保存登录信息
            $update['last_login_time'] = time();
            $update['login_count'] = ['exp', 'login_count+1'];
            $update['last_login_ip'] = $this->request->ip();
            Db::name("AdminUser")->where('id', $auth_info['id'])->update($update);

            // 记录登录日志
            $log['uid'] = $auth_info['id'];
            $log['login_ip'] = $this->request->ip();
            $log['login_location'] = implode(" ", \Ip::find($log['login_ip']));
            $log['login_browser'] = \Agent::getBroswer();
            $log['login_os'] = \Agent::getOs();
            Db::name("LoginLog")->insert($log);
            return $this->success($msg);
        }else{
            $msg['error_id']='1010004';
            $msg['message']='账户密码不正确或被禁用';
            $msg['data']=$data;
            return $this->error($msg);
        }
    }
    /**
     * @title 注册
     * @description 接口说明
     * @author 梁敏
     * @url /index/login/register
     * @method ~
     * @param name:account type:string require:1
     * @param name:password type:string require:1
     * @param name:code type:string require:1
     * @param name:repassword type:string require:1
     * @return error_id:错误id desc:1010001校验失败|账户已存在,1010002添加失败,1010008验证码错误
     *@return token:token
     */
    public function register()
    {
        //接口代码
        $data=input();

        //校验错误
        $validate = new \app\common\validate\AdminUser();
        $v_re = $validate->scene('register')->check($data);//
        if(!$v_re){
            $msg['error_id']='1010001';
            $msg['message']=$validate->getError();
//            $msg['data']=$validate->getError();
            return $this->error($msg);
        }
        $code=Db::name('tinree_code')
            ->where('over_time',">",NOW_TIME)
            ->where('mobile',$data['account'])
            ->where('code_type','register')
            ->where('code',$data['code'])
            ->find();
        if(!$code){
            $msg['error_id']='1010008';
            $msg['message']="验证码错误";
//            $msg['data']=Db::name('tinree_code')->getLastSql();
            return $this->error($msg);
        }
        //添加用户
        $user=new AdminUser();
        $data['mobile']=$data['account'];
        $id=$user->add($data);

        if($id){

            $auth_info=Db::name('admin_user')->where(array('id'=>$id))->find();

            $token=get_token();
            Db::name('admin_user')->where('id',$auth_info['id'])->update(array('token'=>$token));
            $msg['message']="添加成功";
            $msg['token']=$token;
            $msg['data']=user($id);
            //登录记录
            // 保存登录信息
            $update['last_login_time'] = time();
            $update['login_count'] = ['exp', 'login_count+1'];
            $update['last_login_ip'] = $this->request->ip();
            Db::name("AdminUser")->where('id', $auth_info['id'])->update($update);

            // 记录登录日志
            $log['uid'] = $auth_info['id'];
            $log['login_ip'] = $this->request->ip();
            $log['login_location'] = implode(" ", \Ip::find($log['login_ip']));
            $log['login_browser'] = \Agent::getBroswer();
            $log['login_os'] = \Agent::getOs();
            Db::name("LoginLog")->insert($log);

            return $this->success($msg);
        }else{
            $msg['error_id']="1010002";
            $msg['message']="添加失败";
            return $this->error($msg);
        }

    }
    /**
     * @title 更新密码
     * @description 接口说明
     * @author 梁敏
     * @url /index/login/updatepwd
     * @method ~
     * @param name:account type:string require:1
     * @param name:password type:string require:1
     * @param name:repassword type:string require:1
     * @param name:code type:string require:1
     * @return error_id:错误id desc:1010009校验错误,1010010验证码错误,1010011账号不存在,1010012修改失败
     *@return token:token
     */
    public function updatepwd()
    {
        //获取数据
        $data=input();

        //校验错误
        $validate = new \app\common\validate\AdminUser();
        $v_re = $validate->scene('updatepwd')->check($data);//
        if(!$v_re){
            $msg['error_id']='1010009';
            $msg['message']=$validate->getError();
            $msg['data']=$validate->getError();
            return $this->error($msg);
        }
        $old_user=Db::name('admin_user')->where('account',$data['account'])->find();
        if(!$old_user){
            $msg['error_id']='1010011';
            $msg['message']="账号不存在";
            $msg['data']=Db::name('tinree_code')->getLastSql();
            return $this->error($msg);
        }

        $code=Db::name('tinree_code')
            ->where('over_time',">",NOW_TIME)
            ->where('mobile',$data['account'])
            ->where('code_type','updatepwd')
            ->where('code',$data['code'])
            ->find();
        if(!$code){
            $msg['error_id']='1010010';
            $msg['message']="验证码错误";
            $msg['data']="验证码错误";
            return $this->error($msg);
        }

        //添加用户
        $user=new AdminUser();
        $re=$user->updatePassword($old_user['id'],$data['password']);

        if($re!==false){
            $msg['message']="修改成功";
            $msg['data']=$re;
            return $this->success($msg);
        }else{
            $msg['error_id']="1010012";
            $msg['message']="修改失败";
            return $this->error($msg);
        }

    }
    /**
     * @title 修改手机号
     * @description 接口说明
     * @author 李锐志
     * @url /index/login/updatephone
     * @method ~
     * @param name:account type:string require:1 desc:账号
     * @param name:mobile type:string require:1 desc:新手机号
     * @param name:code type:string require:1 desc:验证码
     */

    public function updatephone(){
        //获取输入数据
        $data = input();
        //校验错误
        $validate = new \app\common\validate\AdminUser();
        $v_re = $validate->scene('updatephone')->check($data);//
        if(!$v_re){
            $msg['error_id']='1010013';
            $msg['message']=$validate->getError();
            return $this->error($msg);
        }
        //获取到的手机号和库中的手机如果有匹配记录，说明手机号存在
        $old_user=Db::name('admin_user')->where('account',$data['mobile'])->find();
        if($old_user){
            $msg['error_id']='1010014';
            $msg['message']="该手机号码已存在";
            return $this->error($msg);
        }
        //匹配数据库中的验证码记录
        $code=Db::name('tinree_code')
            ->where('over_time',">",NOW_TIME)
            ->where('mobile',$data['mobile'])
            ->where('code_type','updatephone')
            ->where('code',$data['code'])
            ->find();
        if(!$code){
            $msg['error_id']='1010015';
            $msg['message']="验证码错误";
            $msg['data']="验证码错误";
            return $this->error($msg);
        }
        $data['account']=$data['mobile'];
        //匹配成功则修改
        $result = Db::name('admin_user')->where('id',$data['user_id'])->update($data);
        if($result!==false){
            $msg['message']="修改成功";
            return $this->success($msg);
        }else{
            $msg['error_id']="1010016";
            $msg['message']="修改失败";
            return $this->error($msg);
        }

    }


    /**
     * @title 验证码
     * @description 接口说明
     * @author 梁敏
     * @url /index/login/code
     * @method ~
     * @param name:mobile type:string require:1
     * @param name:code_type type:string require:1 desc:验证码类型register,updatepwd,updatephone
     * @return error_id:错误id desc:0005校验失败 0006添加失败

     */
    public function code()
    {
        //接口代码
        $data=input();
        $messgae = [
            'mobile.require' => '手机号码不能为空',
            'mobile.regex' => '请填写正确的手机号码格式',
            'code_type.require' => '验证码的类型不能为空',
            'code_type.in' => '验证码的类型不正确',
        ];
        $validate = new Validate([
            'mobile'  => 'require|regex:^1[3456789]\d{9}$',
            'code_type'=>"require|in:register,updatepwd,updatephone",
        ],$messgae);

        if (!$validate->check($data)) {
            $msg['error_id']="1010005";
            $msg['message']=$validate->getError();
            //$msg['data']=user($id);
            return $this->error($msg);
        }
        //1分钟
        $m1=1*60;
        $old=Db::name('tinree_code')
            ->where('create_time',">",NOW_TIME-$m1)
            ->where('mobile',$data['mobile'])
            ->where('code_type',$data['code_type'])
            ->find();
//        $msg['data']=Db::name('tinree_code')->getLastSql();
//        return $this->error($msg);
        if($old){
            $msg['error_id']="1010007";
            $msg['message']="最近已发送(1分钟)";
            $msg['data']="最近已发送";
            return $this->error($msg);
        }
        $verify = rand(1236, 9999);//获取随机验证码

        //以下信息自己填以下
        $mobile=$data['mobile'];//手机号
        $argv = array(
            'name'=>'18694047848',     //必填参数。用户账号
            'pwd'=>'9FA6EB4D075A98F84F896CF0D451',     //必填参数。（web平台：基本资料中的接口密码）
            'content'=>'短信验证码为：'.$verify.'，请勿将验证码提供给他人。',   //必填参数。发送内容（1-500 个汉字）UTF-8编码
            'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
            'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
            'sign'=>'青海精灵国旅',    //必填参数。用户签名。
            'type'=>'pt',  //必填参数。固定值 pt
            'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
        );

        //构造要post的字符串
        $flag = 0;
        $params='';//要post的数据
        foreach ($argv as $key=>$value) {
            if ($flag!=0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.= urlencode($value);// urlencode($value);
            $flag = 1;
        }
        $url = "http://web.wasun.cn/asmx/smsservice.aspx?".$params; //提交的url地址
        $con= substr( file_get_contents($url), 0, 1 );  //获取信息发送后的状态
        $argv['code']=$verify;
        $argv['create_time']=NOW_TIME;
        $argv['code_type']=$data['code_type'];

        //一个小时
        $h1=60*60;
        $argv['over_time']=NOW_TIME+$h1;
        Db::name('tinree_code')->insertGetId($argv);
        if($con == '0'){
            $msg['message']="已发送";
//            $msg['data']="";
            return $this->success($msg);
        }else{
            $msg['error_id']="1010006";
            $msg['message']="发送失败";
            return $this->error($msg);
        }

    }
}